package com.example.shiro.demo.shiro;

import com.alibaba.fastjson.JSON;
import com.example.shiro.demo.vo.ActiveUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.SessionKey;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.apache.shiro.web.session.mgt.WebSessionKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <Description> <br>
 *
 * @author renweiping<br>
 * @version 1.0<br>
 * @taskId: <br>
 * @createDate 2019/10/15 10:12 <br>
 * @see com.example.shiro.demo.shiro <br>
 */
public class ShiroUtil {

    private static final Logger log = LoggerFactory.getLogger(ShiroUtil.class);

    /**
     *
     * <p>description: 获取ActiveUser并保存至session中一份</p>

     */
    public static ActiveUser getActiveUser(){
        //从shiro的session中取出activeUser
        Subject subject = SecurityUtils.getSubject();
        //取出身份信息
        log.info( JSON.toJSONString(subject.getPrincipal()))      ;
        ActiveUser activeUser = (ActiveUser) subject.getPrincipal();
        if(activeUser!=null){
            Session session = subject.getSession();
            ActiveUser user = (ActiveUser) session.getAttribute("user");
            if(user==null){
                session.setAttribute("user", activeUser);
            }
            return activeUser;
        }else{
            return null;
        }
    }

    /**
     * 根据sessionid 获取用户信息
     * @param sessionID
     * @param request
     * @param response
     * @return
     */
    public static ActiveUser getActiveUser(String sessionID,HttpServletRequest request,HttpServletResponse response) throws Exception{
        boolean status = false;
        SessionKey key = new WebSessionKey(sessionID,request,response);
        Session se = SecurityUtils.getSecurityManager().getSession(key);
        Object obj = se.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
        //org.apache.shiro.subject.SimplePrincipalCollection cannot be cast to com.hncxhd.bywl.entity.manual.UserInfo
        SimplePrincipalCollection coll = (SimplePrincipalCollection) obj;
        ActiveUser activeUser = (ActiveUser)coll.getPrimaryPrincipal();

        if(activeUser!=null){
            ActiveUser user = (ActiveUser) se.getAttribute("user");
            if(user==null){
                se.setAttribute("user", activeUser);
            }
            return activeUser;
        }else{
            return null;
        }

    }


}

